let init = () => {
    initUeditor()
    initEvent()
}
let initUeditor = function() {
    window.editor = new wangEditor('editor-trigger');
    editor.config.customUpload = true;
    editor.config.customUploadInit = uploadInit;
    editor.create();
}

let initEvent = () => {
    $('#userPic').on('change', onFileChange)
    $('#postArticleBtn').on('click', onPostArticleBtnClick)
    $('#saveUserInfo').on('click', onSaveUserInfoClick)
    $('#updatePasswordBtn').on('click', onUpdatePasswordBtnClick)
    $('#nav-home-tab').on('click', onNavHomeTabClick)
}

//修改头像
let onFileChange = async() => {
    //发送ajax获取token
    let token = (await getToken()).msg
        //找到页面上的这个file文件 获取上传相关信息
    let file = $('[type="file"]')[0].files[0]
        //定义一个时间戳，做这个上传之后文件的名称
    let key = Date.now()
        //创建本次上传的配置信息
    let config = {
        useCdnDomain: true, //启用线上cdn服务器加速
        region: qiniu.region.z0 //指定你这个仓库定义的时候属于哪一个七牛的服务器区域
    }

    let putExtra = null //上传的重置文件，默认不作处理

    //window下面就会有一个七牛对象，返回一个obser对象
    qiniu.upload(file, key, token, putExtra, config).subscribe({
        //详情见七牛的js SDK
        async complete(res) {
            $('[type=file]').siblings('img')
                .attr('src', res.url)

            let addResult = await addUserInfo({ avatar: res.url })
        }
    })
}

//上传文章
let onPostArticleBtnClick = async() => {
    let content = editor.$txt.html()
    let sendStatus = await sendArticle({
        title: $('#title').val(),
        classify: $('#classify').val(),
        content
    })
    if (sendStatus) {
        location.replace('/')
    }
}

//修改签名与主页
let onSaveUserInfoClick = async function() {
    let website = $('#userWebsite').val()
    let sign = $('#userSign').val()

    let data = {}
    website && (data['website'] = website)
    sign && (data['sign'] = sign)

    let addResult = await addUserInfo(data)
    location.replace('/user/info')
}

//修改密码
let onUpdatePasswordBtnClick = async() => {
    let newPassword = $('#newPassword').val()
    let password = $('#oldPassword').val()

    let res = await updatePassword({ newPassword, password })

    if (res.code != 0) {
        alert(res.errorInfo)
    } else {
        sessionStorage.removeItem('userToken')
        location.replace('/login')
    }
}

let onNavHomeTabClick = () => {
    location.replace('/user/info')
}

init()